package classes {
	import UIUtils.uif_json;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;

	public class clt_search {
		
		protected static const GOOGLEKEY: String = 'AIzaSyAdlVaLkt3POcoidnM17kDCq_3IImBFBY8';
		protected static const GOOGLECX	: String = '012760015332305889981:505ns9fuy4m';
		
		public static function search(keyText: String, handle: Function, start: int=1, count: int=10): void {
			var l_count	: int = count>10?10:count;
			var l_end	: int = start + count;
			var _result	: Array = new Array();
			
			function doComplete(e: Event): void {
				var _data: Object = uif_json.d((e.target as URLLoader).data as String);
				if (_data.items) _result = _result.concat(_data.items);
				
				start += l_count;
				if (start >= l_end) handle(_result);
				else getPart(start, l_count);
			}
			
			function doIoError(e: IOErrorEvent): void {
				e.stopPropagation();
			}
			
			function getPart(a_start: int, a_count: int): void {
				var link: String = 'http://vmaya.ru/google/search.php?q=' + keyText + 
					'&key=' + GOOGLEKEY + 
					'&cx=' + GOOGLECX +
					'&start=' + a_start +
					'&num=' + a_count +
					'&imgSize=large&searchType=image';
				
				var loader	: URLLoader = new URLLoader(new URLRequest(encodeURI(link)));
				loader.dataFormat = URLLoaderDataFormat.TEXT;
				loader.addEventListener(Event.COMPLETE, doComplete);
				loader.addEventListener(IOErrorEvent.IO_ERROR, doIoError);
			}
			
			getPart(start, l_count);
		}
	}
}